package top.ed333.mcplugins.configurableevents.requirement;

import me.clip.placeholderapi.PlaceholderAPI;
import org.bukkit.entity.Player;
import org.bukkit.event.Event;
import org.bukkit.event.player.PlayerEvent;
import org.jetbrains.annotations.NotNull;

public class ExpressionReqGroup extends ReqGroup {
    public ExpressionReqGroup(String groupName, @NotNull String ext) {
        super(groupName, ext);
    }

    @Override
    public boolean checkReq(@NotNull Event event) {
        Player player = null;
        if (event instanceof PlayerEvent) {
            player = ((PlayerEvent) event).getPlayer();
        }

        String extExp = PlaceholderAPI.setPlaceholders(player, getExt().toString()).replace(" ",  "");

        return evaluateExpression(extExp);
    }

    @Override
    public String name() {
        return "Expression";
    }

    private static boolean evaluateExpression(String expression) {
        String[] tokens = expression.split(">|<|>=|<=|==");

        boolean result = false;
        if (tokens.length == 3) {
            double operand1 = Double.parseDouble(tokens[0]);
            String operator = tokens[1];
            double operand2 = Double.parseDouble(tokens[2]);

            switch (operator) {
                case ">":
                    result = operand1 > operand2;
                    break;
                case "<":
                    result = operand1 < operand2;
                    break;
                case "==":
                    result = operand1 == operand2;
                    break;
                case ">=":
                    result = operand1 >= operand2;
                    break;
                case "<=":
                    result = operand1 <= operand2;
                    break;
            }
        }
        return result;
    }

}
